var Utils = function () {
	var util = {};
	DT.DEFAULTS.TIMEOUT = 60 * 1000; // 60秒;常量不能通过代码修改

	util.startPageLoading = function (options) {
		options = options || {};
		options.animate = options.animate !== false;
		App.startPageLoading(options);
	}
	util.stopPageLoading = function () {
		App.stopPageLoading();
	}
	util.startLoadingMask = function (options) {
		options = options || {};
		options.animate = options.animate !== false;
		App.blockUI(options);
	}
	util.stopLoadingMask = function (target) {
		App.unblockUI(target);
	}


	DT.DEFAULTS.post = {
		errorFn: function (xhr, error, exception) {
			swal("温馨提示", error);
		}
	};
	util.post = function (param, success, error) {
		if (!param) {
			throw "第一个参数param必传！";
		}
		var successFn = param.success || success;
		var errorFn = param.error || error || DT.DEFAULTS.post.errorFn;
		$.ajax({
			url: param.url,
			data: param.data,
			dataType: 'json',
			type: 'post',
			timeout: param.timeout || DT.DEFAULTS.TIMEOUT,
			success: function (data, status, xhr) {
				if (data.success) {
					successFn && successFn(data);
				} else if (!data.success && data.status == 101) {
					window.location.reload();
				} else if (!data.success && data.status == 403) {
					Utils.toastError(data.msg || "对不起，非本市企业暂无该功能权限");
				} else {
					errorFn && errorFn(xhr, data.msg, false);
				}
			},
			error: function (xhr, error, exception) {
				if ((!error || "error" === error) && xhr !== null && xhr.status !== 200) {
					error = "网络请求失败:" + xhr.status;
				}
				error = error || exception || "操作失败";
				errorFn && errorFn(xhr, error, exception);
			}
		});
	};
	DT.DEFAULTS.postWithLoading = {
		errorFn: function (xhr, error, exception) {
			swal("温馨提示", error);
		}
	};

	util.postWithLoading = function (param, success, error) {
		if (!param) {
			throw "第一个参数param必传！";
		}
		var successFn = param.success || success;
		var errorFn = param.error || error || DT.DEFAULTS.postWithLoading.errorFn;
		util.startPageLoading();
		$.ajax({
			url: param.url,
			data: param.data,
			dataType: 'json',
			type: 'post',
			timeout: param.timeout || DT.DEFAULTS.TIMEOUT,
			success: function (data, status, xhr) {
				util.stopPageLoading();
				if (data.success !== false) {
					successFn && successFn(data);
				} else if (!data.success && data.status == 101) {
					window.location.reload();
				} else if (!data.success && data.status == 403) {
					Utils.toastError(data.msg || "对不起，非本市企业暂无该功能权限");
				} else {
					errorFn && errorFn(xhr, data.msg, false);
				}
			},
			error: function (xhr, error, exception) {
				util.stopPageLoading();
				if ((!error || "error" === error) && xhr !== null && xhr.status !== 200) {
					error = "网络请求失败:" + xhr.status;
				}
				error = error || exception || "操作失败";
				errorFn && errorFn(xhr, error, exception);
			}
		});
	};
	DT.DEFAULTS.postWithMask = {
		errorFn: function (xhr, error, exception) {
			swal("温馨提示", error);
		}
	};

	util.postWithMask = function (param, success, error) {
		if (!param) {
			throw "第一个参数param必传！";
		}
		var successFn = param.success || success;
		var errorFn = param.error || error || DT.DEFAULTS.postWithMask.errorFn;
		util.startLoadingMask();
		$.ajax({
			url: param.url,
			data: param.data,
			dataType: 'json',
			type: 'post',
			timeout: param.timeout || DT.DEFAULTS.TIMEOUT,
			success: function (data, status, xhr) {
				util.stopLoadingMask();
				if (data.success !== false) {
					successFn && successFn(data);
				} else if (!data.success && data.status == 101) {
					window.location.reload();
				} else if (!data.success && data.status == 403) {
					Utils.toastError(data.msg || "对不起，非本市企业暂无该功能权限");
				} else {
					errorFn && errorFn(xhr, data.msg, false);
				}
			},
			error: function (xhr, error, exception) {
				util.stopLoadingMask();
				if ((!error || "error" === error) && xhr !== null && xhr.status !== 200) {
					error = "网络请求失败:" + xhr.status;
				}
				error = error || exception || "操作失败";
				errorFn && errorFn(xhr, error, exception);
			}
		});
	};

	if (window.toastr) {
		toastr.options.hideDuration = 0;
	}

	DT.DEFAULTS.toast = {
		closeButton: true,
		positionClass: "toast-top-center",
		showDuration: 1000,
		hideDuration: 1000,
		timeOut: 3000
	}

	var toast = function (type, message, title, options) {

		if (typeof message === "object") {
			options = message;
			message = options.message;
			title = options.title;
		} else if (typeof title === "object") {
			options = title;
			title = options.title;
		}
		options = $.extend({}, DT.DEFAULTS.toast, options);
		if (options.clearPrevAll) {
			toastr.clear();
			setTimeout(function () {
				toastr[type](message, title, options);
			}, 125)
		} else {
			toastr[type](message, title, options);
		}
	};
	util.clearToasts = function () {
		toastr.clear()
	};
	util.toast = function (type, message, title, options) {
		toast(type, message, title, options);
	};
	util.toastInfo = function (message, title, options) {
		toast("info", message, title, options);
	};
	util.toastSuccess = function (message, title, options) {
		toast("success", message, title, options);
	};
	util.toastWarning = function (message, title, options) {
		toast("warning", message, title, options);
	};
	util.toastError = function (message, title, options) {
		toast("error", message, title, options);
	};


	DT.DEFAULTS.confirm = {
		title: "温馨提示", // 标题
		type: "warning", // 类型
		showCancelButton: true,
		closeOnConfirm: false,
		confirmButtonColor: "#DD6B55",
		confirmButtonText: "确定",
		cancelButtonText: "取消"
	}
	// confirm方法 两个参数必传
	util.confirm = function (param, callback) {
		if (!param) {
			throw "第一个参数param必传！";
		}
		if (!callback) {
			throw "第二个参数callback必传！";
		}
		if (typeof param === "string") {
			swal($.extend({}, DT.DEFAULTS.confirm, {
				text: param
			}), callback);
		} else {
			var def = DT.DEFAULTS.confirm
			swal($.extend({}, def, {
				title: param.title || def.title,
				text: param.text,
				html: param.html || false, // true: 解析title标题和text中的html字符串
				confirmButtonText: param.confirmButtonText || def.confirmButtonText,
				cancelButtonText: param.cancelButtonText || def.cancelButtonText
			}), callback);
		}
	}
	// 打开弹出框 ; param参数必传
	util.openBox = function (config, callback, subWinCallback) {
		if (!config) {
			throw "第一个参数config必传！";
		}
		callback = callback || config.callback;
		subWinCallback = subWinCallback || config.subWinCallback;
		var ctx = config.ctx || window;
		var url = config.url || "";
		if (window.dtLayerIndex) {
			var deep = 0;
			var win = window;
			while (win !== ctx) {
				deep++;
				win = ctx.parent;
			}
			url = url + "#" + window.dtLayerIndex + "." + deep;
		}
		var area = config.area || ['760px', '300px'];
		var cw = document.documentElement.clientWidth;
		if (cw > 1368 && config.scaleWidth !== false) {
			var w = parseInt(area[0]) * cw / 1368;
			area[0] = Math.floor(w || 100) + "px";
		}
		var options = {
			title: config.title,
			type: 2,
			area: area,
			//fixed : false, //不固定
			fixed: true,
			scrollbar: false,
			maxmin: config.maxmin === true,
			content: url,
			anim: -1,
			moving: function (layero) {
				if (ctx.select2LayerMovingCallback) {
					ctx.select2LayerMovingCallback(layero)
				}
			},
			resizing: function (layero) {
				if (ctx.select2LayerResizingCallback) {
					ctx.select2LayerResizingCallback(layero)
				}
			},
			success: function (layero, index) {
				try {
					var subWin = ctx.layer.getContentWindow(index);
					subWin.dtLayerIndex = index
					subWin.dtLayerCallback = subWinCallback
				} catch (e) {
				}
				if (config.autoHeight) {
					ctx.layer.iframeAuto(index, config.autoHeight || $(window).height() * 0.85);
				}
				callback && callback(layero, index, subWin);
			}
		};
		var m = {
			callback: 1,
			subWinCallback: 1,
			ctx: 1,
			url: 1,
			area: 1,
			autoHeight: 1,
			moving: 1,
			resizing: 1,
			success: 1
		}
		for (var k in config) {
			if (config.hasOwnProperty(k) && !m[k]) {
				options[k] = config[k];
			}
		}
		return ctx.layer.open(options);
	}
	util.appendTifilter = function (el, url) {
		var htmlEl = $.type(el) === 'object' && (el.nodeType || el.length && el[0].nodeType);
		var filter = undefined;
		if (htmlEl) {
			filter = $(el).attr("data-ti-filter");
		}

		if (!filter) {
			filter = $("li.active a[data-ti-filter]").attr("data-ti-filter");
		}
		return !filter || "all" === filter ? url : url + (url.indexOf("?") >= 0 ? "&" : "?") + "_ti_filter=" + (filter || "")
	}

	!function () {

		util.treeNodesToList = function (nodes, childKey, arrList) {
			$.each(nodes, function (index, item) {
				arrList.push(item.data);
				var children = item[childKey];
				if (children && children.length) {
					util.treeNodesToList(children, childKey, arrList);
				}
			});
			return arrList;
		};

		util.listToTree = function (arr, idKey, pIdKey, childKey, deepCopy) {
			var i, l;
			if (Object.prototype.toString.apply(idKey) === "[object Object]") { //
				var config = idKey;
				idKey = config.idKey || "id";
				pIdKey = config.pIdKey || "pid";
				childKey = config.childKey || "children";
			} else {
				idKey = idKey || "id";
				pIdKey = pIdKey || "pid";
				childKey = childKey || "children";
			}
			if (!idKey || idKey === "" || !arr) return [];

			if (Object.prototype.toString.apply(arr) === "[object Array]") { // 是数组
				arr = deepCopy ? JSON.parse(JSON.stringify(arr)) : arr;
				var r = [];
				var tmpMap = {};
				for (i = 0, l = arr.length; i < l; i++) {
					tmpMap[arr[i][idKey]] = arr[i];
				}
				for (i = 0, l = arr.length; i < l; i++) {
					if (tmpMap[arr[i][pIdKey]] && arr[i][idKey] !== arr[i][pIdKey]) {
						if (!tmpMap[arr[i][pIdKey]][childKey])
							tmpMap[arr[i][pIdKey]][childKey] = [];
						tmpMap[arr[i][pIdKey]][childKey].push(arr[i]);
					} else {
						r.push(arr[i]);
					}
				}
				return r;
			} else {
				return [arr];
			}
		};

		var _visitFn = function (fn, childKey, prefix) {
			var visitFn = function (result, data, depth, _prefix, parent) {
				for (var i = 0; i < data.length; i++) {
					var item = data[i];
					var position = i === data.length - 1 ? 1 : i === 0 ? -1 : 0;
					result.push(fn(item, depth, _prefix, parent, position));
					var children = item[childKey];
					if (children && children.length) {
						visitFn(result, children, depth + 1, _prefix + "" + prefix, item);
					}
				}
			};
			return visitFn;
		};
		/**
		 *
		 * @param arr
		 * @param fn function(item,depth,prefix,parent,position)
		 * @param idKey
		 * @param pIdKey
		 * @param prefix
		 * @returns {Array}
		 */
		util.visitTreeList = function (arr, fn, idKey, pIdKey, prefix, deepCopy) {
			var data = util.listToTree(arr, idKey, pIdKey, "__children", deepCopy === undefined ? true : deepCopy);
			var result = [];
			if (data && data.length) {
				_visitFn(fn, "__children", prefix)(result, data, 0, "");
			}
			return result;
		};
		util.visitTreeNodes = function (nodes, fn, childKey, prefix) {
			var result = [];
			if (nodes && nodes.length) {
				_visitFn(fn, childKey, prefix)(result, nodes, 0, "", 0);
			}
			return result;
		};
		/**
		 *
		 * @param zTreeObj
		 * @param nodes
		 * @param fn function(item,depth,prefix,parent,position)
		 * @param prefix
		 * @returns {Array}
		 */
		util.visitZTreeNodes = function (zTreeObj, nodes, fn, prefix) {
			var childKey = zTreeObj.setting.data.key.children;
			if (Object.prototype.toString.apply(nodes) === "[object Function]") {
				prefix = fn;
				fn = nodes;
				nodes = zTreeObj.getNodes();
			}
			var result = [];
			if (nodes && nodes.length) {
				_visitFn(fn, childKey, prefix)(result, nodes, 0, "", 0);
			}
			return result;
		};

		function toSelectFn(id, pid, idKey, nameKey, dataKey, edit, showAll) {
			var nameFn = Object.prototype.toString.apply(nameKey) === "[object Function]" ? nameKey : function (item, selected) {
				return item[nameKey] + (selected ? " √" : "");
			};
			var dataFn = Object.prototype.toString.apply(dataKey) === "[object Function]" ? dataKey : dataKey ? function (item) {
				return item[dataKey];
			} : function (item) {
				return item;
			};

			var selfPath = {};
			if (id !== null && id !== "" && id !== undefined) {
				selfPath[id] = 1;
			}
			if (edit) {
				if (showAll === undefined) {
					showAll = false;
				}
				return function (item, depth, prefix, parent, position) {
					var data = dataFn(item), idVal = data[idKey], attribs = idVal === pid ? " selected" : "";
					var ok = true;
					if (selfPath[idVal]) {
						if (!showAll) {
							return "";
						}
						attribs += " disabled";
					} else if (parent) {
						if (selfPath[dataFn(parent)[idKey]]) {
							if (!showAll) {
								return "";
							}
							attribs += " disabled";
							selfPath[idVal] = 1;
						}
					}
					prefix = prefix ? prefix + (position === 1 ? "└─ " : "├─ ") : "";
					return '<option value="' + idVal + '"' + attribs + '>' + prefix + nameFn(data, idVal === pid) + '</option>';
				}
			} else {
				return function (item, depth, prefix, parent, position) {
					var data = dataFn(item), idVal = data[idKey], attribs = idVal === pid ? " selected" : "";
					prefix = prefix ? prefix + (position === 1 ? "└─ " : "├─ ") : "";
					return '<option value="' + idVal + '"' + attribs + '>' + prefix + nameFn(data) + '</option>';
				};
			}
		}

		util.zTreeNodesToSelect = function (zTreeObj, id, pid, options) {
			var idKey = options.idKey || "id";
			var nameKey = options.nameKey || "name";
			var showAll = options.showAll;
			var edit = options.edit;
			var nodes = options.nodes || zTreeObj.getNodesByFilter(function (node) {
				return node.level === 1;
			}, false);
			var fn = toSelectFn(id, pid, idKey, nameKey, null, edit, showAll);
			return Utils.visitZTreeNodes(zTreeObj, nodes, fn, "　");
		};

		util.treeNodesToSelect = function (nodes, id, pid, options) {
			var idKey = options.idKey || "id";
			var nameKey = options.nameKey || "name";
			var dataKey = options.dataKey;
			var childKey = options.childKey || "subNodes";
			var showAll = options.showAll;
			var edit = options.edit;
			return Utils.visitTreeNodes(nodes, toSelectFn(id, pid, idKey, nameKey, dataKey, edit, showAll), childKey, "　");
		};
	}();

	util.arrayToMap = function (arr, idKey, valKey) {
		var m = {}
		var valueFn = Object.prototype.toString.apply(valKey) === "[object Function]" ? valKey : Object.prototype.toString.apply(valKey) === "[object String]" ? function (item) {
			return item[valKey];
		} : valKey === undefined ? function (item) {
			return item;
		} : function () {
			return valKey;
		};

		$.each(arr, function (i, o) {
			m[o[idKey]] = valueFn(o);
		});
		return m;
	}
	util.setChecked = function (checked, name, ctxEl) {
		ctxEl = $(ctxEl || "body")
		ctxEl.find("input[name='" + name + "']").each(function (i, e) {
			e.checked = !!checked;
		})
	};

	util.toggleChecked = function (name, ctxEl) {
		ctxEl = $(ctxEl || "body")
		ctxEl.find("input[name='" + name + "']").each(function (i, e) {
			e.checked = !e.checked;
		})
	};
	util.formatDate = function (date, format, def) {
		if (date) {
			format = format || 'yyyy-MM-dd HH:mm:ss';
			if (typeof date === 'number') {
				return new Date(date).format(format)
			}
			if (typeof date === 'string') {
				return new Date(date.replace(/-/g, "/").replace(/\..*$/g, "")).format(format)
			}
			if (typeof date === 'object' && date.getFullYear && date.getMilliseconds) {
				return date.format(format)
			}
		}
		return def;
	}
	util.prettyFormatDate = function (date, format, fullFormat, def) {
		if (date) {
			if (typeof date === 'number') {
				return new Date(date).prettyFormat(format, fullFormat)
			}
			if (typeof date === 'string') {
				return new Date(date.replace(/-/g, "/")).prettyFormat(format, fullFormat)
			}
			if (typeof date === 'object' && date.getFullYear && date.getMilliseconds) {
				return date.prettyFormat(format, fullFormat)
			}
		}
		return def;
	}

	return util;
}();

DT.DEFAULTS.postWithLoading = {
	errorFn: function (xhr, error, exception) {
		Utils.toastError(error);
	}
};
DT.DEFAULTS.toast = {
	closeButton: false,
	positionClass: "toast-top-center",
	showDuration: 1000,
	hideDuration: 1000,
	timeOut: 3000,
	showMethod: 'fadeIn' //fadeIn, slideDown, and show are built into jQuery
};

/**
 * 附件上传表单验证
 */
DT.Uploader = {
  validate: function (ctx) {
    var result = true;
    (ctx || $(document.body)).find("div.ditop-uploader").each(function () {
      var $ele = $(this), $uploader = $ele.data("uploader"),
        fileCount = $ele.data('fileCount') || 0, minFileNum = $ele.data("minFileNum"), stats = $uploader.getStats();
      if (stats.progressNum > 0) {
        result = false;
      }
    });
    // if(!result)Utils.toastError("文件正在上传, 请等待上传完毕后提交。");
		if(!result){
      Utils.toastError("文件正在上传, 请等待上传完毕后提交。");
		}
    return result;
  }
};

DT.DEFAULTS.validateForm = {
	beforeSerialize: "_dtBeforeSerialize",
	ignore: ":hidden:not(.needValidate),.webuploader-element-invisible,.noValidate",
	errorElement: 'span',
	errorClass: 'help-block help-block-error',
  invalidHandler:function(form,validator){
    //只聚焦第一个错误信息
		if(validator.errorList.length > 0){
      validator.errorList[0].element.focus();
      //关于附件的定位，待研究
      //$(".aptTcontent").stop(true);
			//var container = $(".aptTcontent");
      //container.animate({scrollTop: $("input[name='"+validator.errorList[0].element.name+"']").closest("table").offset().top - container.offset().top + container.scrollTop()}, 1000);
		}
  },
	errorPlacement: function (error, element) {
		var $element = $(element);
		if ($element.is(".up-fileIds")) {
			var $ele = $element.closest("div.ditop-uploader");
			try {
				var el = $ele.data("fnFindStatusEl")();
				el && el.html(error.text());
				return el;
			} catch (e) {
			}
		}
		var icon = $element.closest('.form-group').find('.help-block');

		icon = icon.length == 0 ? $element.closest('.dt-pair').find(".help-block") : icon;

		icon.html(error.text())
	},
	highlight: function (element) {
		$(element).closest('.dt-pair,.form-group').addClass('has-error');
		/*$(element).closest('.dt-pair,.form-group').addClass('has-error');*/
	},
	unhighlight: function (element) {
		/* $(element).closest('.dt-pair,.form-group').removeClass('has-error');*/
	},
	success: function (label, element) {
		var $element = $(element);
		$element.closest('.dt-pair,.form-group').removeClass('has-error');//.addClass('has-success');
		if ($element.is(".up-fileIds")) {
			var $ele = $element.closest("div.ditop-uploader");
			try {
				var el = $ele.data("fnFindStatusEl")();
				el && el.html();
				return el;
			} catch (e) {
			}
		}
		var icon = $element.parent('.input-icon').children('i');
		icon.removeClass("fa-warning").addClass("fa-check");
	}
}


;(function () {

	var upAndDown = function (ele, option) {
		// var _this_=this;
		// _this_.DEFAULT={
		//   height:40
		// };
		// _this_.setting=$.extend(true,{},_this_.DEFAULT,option);

		upAndDown.prototype.init = function () {
			ele.mouseover(function () {
				$(this).find(".upDown").removeClass("context-wrap").addClass("on");
			});

			ele.mouseout(function () {
				$(this).find(".upDown").removeClass("on").addClass("context-wrap");
			});

			// var hi=ele.outerHeight();
			// if (hi>40){
			//   ele.css("height",this.setting.height+"px");
			//   var isFirst=true;
			//   ele.find("b").click(function () {
			//     if(isFirst){
			//       ele.css("height",hi+"px");
			//       $(this).css("width", "36px");
			//       $(this).css("position", "static");
			//       $(this).text("收起");
			//       isFirst = false;
			//     } else {
			//       ele.css("height", "40px");
			//       $(this).css("width", "6em");
			//       $(this).css("position", "absolute");
			//       $(this).text("展开");
			//       isFirst = true;
			//     }
			//   });
			// }else {
			//   ele.find("b").hide();
			// }
		}
	};
	$.fn.extend({
		upAndDown: function (option) {
			this.each(function () {
				new upAndDown($(this), option).init();
			});
		}
	});


	/**
	 * 验证码,支持手机号和邮件
	 * 使用示例:  $("#gCode").veriCode({url: '/p/ryBaseInfo/sendMns',countDown:60, targetName: "mobile"});
	 * @param ele
	 * @param opt
	 * countDown: 3,//倒计时总数
	 * url: "",//后台发送验证码的url
	 * targetName: "mobile"//邮箱地址或手机号的input的name
	 */
	var veriCode = function (ele, opt) {
		var _this_ = this;
		this.DEFAULT = {
			countDown: 3,//倒计时总数
			url: "",//后台发送验证码的url
			targetName: "mobile"//邮箱地址或手机号的input的name
		}

		var i;
		veriCode.prototype.init = function () {
			ele.click(function () {
				_this_.chk();
			});
		};

		veriCode.prototype.chk = function () {
			_this_.setting = $.extend(true, {}, _this_.DEFAULT, opt);
			var isValid = $("input[name='" + _this_.setting.targetName + "']").valid();
			if (isValid) {
				ele.addClass("gCode_gray");
				_this_.render();
			}
		}

		veriCode.prototype.render = function () {
			ele.off('click');
			_this_.send();
			i = setInterval(function () {
				if (_this_.setting.countDown == 0) {
					ele.removeClass("gCode_gray");
					window.clearInterval(i);
					ele.text("重新获取").click(_this_.chk);
					return;
				}
				ele.text((_this_.setting.countDown) + "s");
				_this_.setting.countDown--;

			}, 1000);

		}
		veriCode.prototype.send = function () {
			if (_this_.setting.url) {
				Utils.post({
					url: _this_.setting.url,
					data: {"targatNo": $("input[name='" + _this_.setting.targetName + "']").val()},
				}, function (data) {
					console.debug(data)
				}, function (data) {
					console.debug(data)
				})
			} else {
				console.error("缺少url参数");
			}
		}
	}

	$.fn.extend({
		veriCode: function (opt) {
			new veriCode($(this), opt).init();
		}
	});

	/**
	 * 人员选择插件
	 * @param callback
	 */
	var personSelect = function (callback) {
		Utils.openBox({
			title: '选择人员',
			area: ['900px', '556px'],
			ctx: parent,
			scaleWidth: false,
			url: '/p/common/personSelect',
			subWinCallback: function (data) {
				callback && callback(data)
			}
		})
	};

	$.fn.extend({
		personSelect: function (callback) {
			var $this = $(this);
			window.ps_compId = $this.data("compid");//限制只能选某个企业下的人员
			window.ps_multiple = $(this).data("multiple");//是否支持多选
            window.pa_filterIds = $("#compManagerIds").val();
			$this.click(function () {
				window.ps_values = $this.data("values");
				personSelect(callback)
			})
		}
	});

	//外省选择人员
    var outProPerSelect = function (callback) {
        Utils.openBox({
            title: '选择人员',
            area: ['900px', '556px'],
            ctx: parent,
            scaleWidth: false,
            url: '/p/common/outProPersonSelect',
            subWinCallback: function (data) {
                callback && callback(data)
            }
        })
    };

    $.fn.extend({
        outProPerSelect: function (callback) {
            var $this = $(this);
            window.ps_compId = $this.data("compid");//限制只能选某个企业下的人员
            window.ps_multiple = $(this).data("multiple");//是否支持多选
            window.pa_filterIds = $("#compManagerIds").val();
            $this.click(function () {
                window.ps_values = $this.data("values");
                outProPerSelect(callback)
            })
        }
    });

	var personAptSelect = function (callback) {
		Utils.openBox({
			title: '选择人员',
			area: ['900px', '556px'],
			ctx: parent,
			scaleWidth: false,
			url: '/p/common/personAptSelect',
			subWinCallback: function (data) {
				callback && callback(data)
			}
		})
	};

	$.fn.extend({
		personAptSelect: function (callback) {
			var $this = $(this);

			window.pa_compId = $this.data("compid");//限制只能选某个企业下的人员
			window.pa_type = $this.data("type");//大类别,例:注册人员,专业人员等
			window.pa_profid = $this.data("profid");//专业id
			window.pa_multiple = $this.data("multiple");//是否支持多选
			window.realFlag = $this.data("realflag");//人员是否实名制
			$this.click(function () {
				var certArray = [];
				$("input.filter-cert").each(function () {
					certArray.push($(this).val());
				})

				window.pa_values = $this.data("values");
				window.pa_filterIds = certArray.join(',');//过滤筛选人员id
				personAptSelect(callback)
			})
		}
	});


	var leaderSelect = function (callback) {
		Utils.openBox({
			title: '选择技术负责人',
			area: ['900px', '556px'],
			ctx: parent,
			scaleWidth: false,
			url: '/p/common/leaderSelect',
			subWinCallback: function (data) {
				callback && callback(data)
			}
		})
	};

	$.fn.extend({
		leaderSelect: function (callback) {
			var $this = $(this);
			window.compId = $this.data("compid");//限制只能选某个企业下的人员
			window.multiple = $this.data("multiple");//是否支持多选
			// window.selvals = $this.data("selvals");//默认选中项
			$this.click(function () {
				window.pl_values = $this.data("values");
                legalSelect(callback)
			})
		}
	});


    var legalSelect = function (callback) {
        Utils.openBox({
            title: '选择企业法定代表人',
            area: ['900px', '556px'],
            ctx: parent,
            scaleWidth: false,
            url: '/p/common/legalSelect',
            subWinCallback: function (data) {
                callback && callback(data)
            }
        })
    };

    $.fn.extend({
        legalSelect: function (callback) {
            var $this = $(this);
            window.cmName = $this.data("cmName");//限制只能选某个企业下的人员
            window.multiple = $this.data("multiple");//是否支持多选
            // window.selvals = $this.data("selvals");//默认选中项
            $this.click(function () {
                window.pl_values = $this.data("values");
                legalSelect(callback)
            })
        }
    });

	var safetySelect = function (callback) {
		Utils.openBox({
			title: '选择企业安管人员',
			area: ['900px', '556px'],
			ctx: parent,
			scaleWidth: false,
			url: '/p/common/safetyPersonSelect',
			subWinCallback: function (data) {
				callback && callback(data)
			}
		})
	};

	$.fn.extend({
		safetySelect: function (callback) {
			var $this = $(this);
			window.compId = $this.data("compid");//限制只能选某个企业下的人员
			window.multiple = $this.data("multiple");//是否支持多选
			// window.selvals = $this.data("selvals");//默认选中项
			$this.click(function () {
				window.pl_values = $this.data("values");
				window.filterIds = $this.data("filterids");//过滤筛选人员id
				safetySelect(callback)
			})
		}
	});

	//平台角色选择
	var roleSelect = function (callback) {
		Utils.openBox({
			title: '选择角色',
			area: ['360px', '500px'],
			ctx: parent,
			// maxmin: true,
			url: '/p/common/roleSelect',
			subWinCallback: function (data) {
				callback && callback(data)
			}
		})
	};

	$.fn.extend({
		roleSelect: function (callback) {
			var $this = $(this);
			window.role_multiple = $this.data("multiple");//是否支持多选
			window.role_plat = $this.data("plat");//展示哪些平台的角色
			$this.click(function () {
				if (!window.role_plat) {
					Utils.toastError("平台代码不能为空!");
					return;
				}
				roleSelect(callback)
			})
		}
	});

//企业资质选择
	var qyAptSelect = function (qyType, callback) {

		var url = qyType == '' || qyType == undefined ? '/p/common/qyAptSelectPage' : '/p/common/qyAptSelectPage/' + qyType;
		Utils.openBox({
			title: '选择资质',
			area: ['900px', '556px'],
			scaleWidth: false,
			ctx: parent,
			// maxmin: true,
			url: url,
			subWinCallback: function (data) {
				callback && callback(data)
			}
		})
	};


	$.fn.extend({
		qyAptSelect: function (callback) {
			var $this = $(this);

			var qyType = $this.data("type");
			window.ps_isfirst = $this.data("isfirst") != undefined ? $this.data("isfirst") : "";
			window.ps_aptids = $this.data("aptids") != undefined ? $this.data("aptids") : "";

			$this.click(function () {
				qyAptSelect(qyType, callback)
			})
		}
	});


})(jQuery);

//art-template 添加自定义方法
//日期格式化
template.defaults.imports.formatDate = function (time, format, def) {
	if (time && typeof time == 'number') {
		return new Date(time).format(format)
	}else if (time && typeof time == 'string') {
    time = time.substring(0,10);
	}
	return time || def;
};

//2017-10-10 2017年10月10日
template.defaults.imports.formatStrDate = function (date, format) {
	if (!date) {
		return ""
	} else {
		date = date.replace(/-/g, "/");
	}
	date = new Date(date);
	return date.format(format)
}

template.defaults.imports.prettyDot = function (str) {
	if(str){
		return str.replace(/,/g,'<br/>')
	}
	return str||"-";
}

//通过身份证获取年龄
template.defaults.imports.getAge = function (identityCard) {
  if(identityCard){
    var len = (identityCard + "").length;
    if (len == 0) {
      return 0;
    } else {
      if ((len != 15) && (len != 18)){
        return 0;
      }
    }
    var strBirthday = "";
    if (len == 18){
      strBirthday = identityCard.substr(6, 4) + "/" + identityCard.substr(10, 2) + "/" + identityCard.substr(12, 2);
    }
    if (len == 15) {
      strBirthday = "19" + identityCard.substr(6, 2) + "/" + identityCard.substr(8, 2) + "/" + identityCard.substr(10, 2);
    }
    var birthDate = new Date(strBirthday);
    var nowDateTime = new Date();
    var age = nowDateTime.getFullYear() - birthDate.getFullYear();
    if (nowDateTime.getMonth() < birthDate.getMonth() || (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())) {
      age--;
    }
    return age;
  }
  return "-";
}


/*var area = ['300px', '200px'];*/
var area = ['300px'];
var topTitle = "提示";
//公共消息组件
var CompUtils = {
	success: function (title, countdown) {
		layer.open({
			title: topTitle,
			skin: "dt-success",
			icon: 1,
			type: 0,
			area: area,
			btn: ['确定'], //按钮,
			content: "<div class='dt_confirm'>" + title + "</div>",
		});
	},
	countdownSuccess: function (title, countdown, callback) {
		layer.open({
			title: topTitle,
			closeBtn: 0,
			skin: "dt-success-countdown",
			icon: 1,
			type: 0,
			area: area,
			btn: ['<span class="countdown"><span class="second">' + countdown + '</span> s后自动关闭</span>'], //按钮,
			content: "<div class='dt_confirm'>" + title + "</div>",
			yes: function (index, layero) {
				window.clearInterval(i);
				layer.close(index); //如果设定了yes回调，需进行手工关闭
			},
			end: function (index) {
				window.clearInterval(i);
			}
		});

		i = setInterval(function () {
			countdown = --countdown;
			if (countdown === 0) {
				callback && callback();
				window.clearInterval(i);
				layer.closeAll();
			}
			$(".second").html(countdown);
		}, 1000);
	},
	confirm: function (optoin, btn1Callback, btn2Callback) {
		layer.open({
			title: topTitle,
			closeBtn: 0,
			skin: "dt-confirm",
			icon: 0,
			type: 0,
			area: optoin.area || ['500px'],
			btn: optoin.btn, //按钮
			content: "<div class='dt_confirm'>" + optoin.title + "</div>",
			yes: function (index, layero) {
				btn1Callback && btn1Callback();
				layer.close(index); //如果设定了yes回调，需进行手工关闭
			},
			btn2: function (index, layero) {
				btn2Callback && btn2Callback();
			}
		});
	},
	confirmPlus: function (optoin, btn1Callback, btn2Callback) {
		layer.open({
			title: topTitle,
			closeBtn: 1,
			skin: "dt-confirm",
			/*	icon: 0,*/
			type: 0,
			area: optoin.area || ['500px'],
			btn: optoin.btn, //按钮
			content: "<div class='dt_confirm_plus_title'>" + optoin.title + "</div><div class='dt_confirm_plus_tip'>" + (optoin.tip || '') + "</div>",
			yes: function (index, layero) {
				btn1Callback && btn1Callback();
				layer.close(index); //如果设定了yes回调，需进行手工关闭
			},
			btn2: function (index, layero) {
				btn2Callback && btn2Callback();
			}
		});
	},
	error: function (title, yesFn, area) {
		layer.open({
			title: topTitle,
			closeBtn: 0,
			skin: "dt-error",
			icon: 2,
			type: 0,
			area: area,
			btn: ['确定'], //按钮
			content: "<div class='dt_confirm'>" + title + "</div>",
			yes: function (index, layero) {
				layer.close(index); //如果设定了yes回调，需进行手工关闭
				yesFn && yesFn();
			}
		});
	},
	postErrorFn: function (data) {
		/*debugger
        if (data.responseJSON.status && data.responseJSON.status == 10001) {
          Utils.toastError(data.responseJSON.msg);
          return false
        }*/
		if (data.responseJSON.msg) {
			Utils.toastError("操作失败：" + data.responseJSON.msg);
		} else {
			Utils.toastError("请求失败");
		}
	}



};
;(function () {

	$.fn.serializeJs = function () {
		var serializeObj = {}, files={};
		var array = this.serializeArray();
		var $this = this;
		$(array).each(function () {
			if (this.name.match(/bifile_*/g)) {
				files[this.name] = this.value;
			} else {
				if (serializeObj[this.name]) {
					if ($.isArray(serializeObj[this.name])) {
						serializeObj[this.name].push(this.value);
					} else {
						serializeObj[this.name] = [serializeObj[this.name], this.value];
					}
				} else {
					var sv = $this.find("select[name='" + this.name + "']").find("option:selected").text();
					if ($.trim(sv)!="") {
						serializeObj[this.name + "Txt"] = sv;
					}
					if($.trim(this.value)!=""){
						serializeObj[this.name] = this.value;
					}

				}
			}
		});
		var arrfiles = Object.keys(files);
		if (arrfiles.length) {serializeObj["file"] = JSON.stringify(files);}

		return serializeObj;
	};

})(jQuery)

//数据完整性校验
function checkDataComplete() {
  var flag = true;
  $("tr[data-complete]").closest(".Science").find(".help-block").html('');
  $("tr[data-complete]").each(function () {
    var _this_ = $(this);
    var msg = _this_.data("msg");
    var isComplete = _this_.data("complete");
    var msgCon = _this_.closest(".Science").find(".help-block");
    if (!isComplete) {
      flag = false;
      msgCon.html(msg);
    }
  });
  return flag;
}

//证书编号和注册编号重复性校验
function repeatfn(data){
  var arrCert = [],arrCertManagerNo = [],certSwitch = true;
  data = eval("(" + data + ")");
  for (var key in data) {
    if (data[key].length > 0) {
      data[key].forEach(function(item){
        arrCert.push(item.certCertNo);
        if(item.certManagerNo){
          arrCertManagerNo.push(item.certManagerNo);
				}
      })
    }
  }
  var nary=arrCert.sort(),mary=arrCertManagerNo.sort();
 /* if(nary.length > 1){
    for(var i=0;i<nary.length;i++){
      if (nary[i]==nary[i+1]){
        certSwitch = false;
        Utils.toastError("同一证书编号信息不能重复添加");
      }
    }
	}*/

  if(mary.length > 1){
    for(var i=0;i<mary.length;i++){
      if (mary[i]==mary[i+1]){
        certSwitch = false;
        Utils.toastError("同一注册编号信息不能重复添加");
      }
    }
	}

  return certSwitch;
}

//表格合并
function mergeTable(tb, stacol, endcol, bool, num) {
	var end;
	var i = 0;
	var j = 0;
	var rowCount = tb.rows.length;
	var colCount = tb.rows[0].cells.length;
	var obj1 = null;
	var obj2 = null;
	var n = 5;
	var count = new Array();
	for (i = 0; i < rowCount; i++) {
		for (j = 0; j < colCount; j++) {
			if (typeof (tb.rows[i].cells[j]) != "undefined") {
				tb.rows[i].cells[j].id = "tb__" + i + "_" + j
			}
		}
	}
	if (typeof (num) != "undefined") {
		obj1 = document.getElementById("tb__0_" + (num - 1).toString());
		for (var t = 1; t < rowCount; t++) {
			obj2 = document.getElementById("tb__" + t.toString() + "_" + (num - 1).toString());
			if (obj1.innerHTML == obj2.innerHTML) {
				obj1.rowSpan++;
				obj2.parentNode.removeChild(obj2)
			} else {
				count[t] = n;
				obj1 = document.getElementById("tb__" + t.toString() + "_" + (num - 1).toString())
			}
		}
	}
	for (i = 0; i < colCount; i++) {
		if (bool) {
			if (i + 1 < stacol || i + 1 > endcol) {
				continue
			}
		} else {
			if (i + 1 > stacol && i + 1 < endcol) {
				continue
			}
		}
		obj1 = document.getElementById("tb__0_" + i.toString());
		for (j = 1; j < rowCount; j++) {
			obj2 = document.getElementById("tb__" + j.toString() + "_" + i.toString());
			if (typeof (count[j]) != "undefined") {
				if (count[j] != n) {
					if (obj1.innerHtml == obj2.innerHtml) {
						obj1.rowSpan++;
						obj2.parentNode.removeChild(obj2)
					} else {
						obj1 = document.getElementById("tb__" + j.toString() + "_" + i.toString())
					}
				} else {
					obj1 = document.getElementById("tb__" + j.toString() + "_" + i.toString())
				}
			} else {
				if (obj1 && obj2 && obj1.innerHTML == obj2.innerHTML) {
					obj1.rowSpan++;
					obj2.parentNode.removeChild(obj2)
				} else {
					obj1 = document.getElementById("tb__" + j.toString() + "_" + i.toString())
				}
			}
		}
	}
}


//证件类型
function getCardType(staffCardTypeId,staffCardnoId,staffSexId,staffBirthdayId) {
    var staffCardType = $("#"+staffCardTypeId + ' option:selected').val(),
    staffCardno = $("#"+staffCardnoId),staffSex = $("#"+staffSexId),staffBirthday = $("#"+staffBirthdayId);
  if (staffCardType == 'RY_ZJLX_0001') {
      staffCardno.attr("data-rule-idcard", true);
      staffSex.attr("disabled", "disabled");
      staffBirthday.attr("disabled", "disabled");
  } else {
      staffCardno.removeAttr("data-rule-idcard");
      staffSex.removeAttr("disabled");
      staffBirthday.removeAttr("disabled");
  }
    staffCardno.val("");
    staffSex.val("");
    staffBirthday.val("");
}

//进赣人员身份证号校验
function getCardNo(staffCardTypeId,staffCardnoId,staffSexId,staffBirthdayId) {
    var staffCardType = $("#"+staffCardTypeId + ' option:selected').val(),
    staffCardno = $("#"+staffCardnoId),
    staffSex = $("#"+staffSexId),staffBirthday = $("#"+staffBirthdayId);
  if (staffCardType == "") {
    Utils.toastWarning("请选择证件类型!");
    staffCardno.val("");
  }else if(staffCardType == "RY_ZJLX_0001"){
    staffSex.val(getSex(staffCardno.val())).attr("disabled", "disabled");
    staffSex.siblings( "span.help-block" ).html("");
    staffBirthday.val(getBirth(staffCardno.val())).attr("disabled", "disabled");
    staffBirthday.siblings( "span.help-block" ).html("");
  }
}

function getBirth(idCard) {
  var birthday = "";
  if(idCard != null && idCard != ""){
    if(idCard.length == 15){
      birthday = "19"+idCard.slice(6,12);
    } else if(idCard.length == 18){
      birthday = idCard.slice(6,14);
    }
    birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
    //通过正则表达式来指定输出格式为:1990-01-01
  }
  return birthday;
}

function getSex(idCard) {
  var sexStr = '';
  if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
    sexStr = 'RY_XB_0001';
  }
  else {
    sexStr = 'RY_XB_0002';
  }
  return sexStr;
}

;(function () {

    $.fn.serializeJson = function () {
        var serializeObj = {}, files = {};
        var array = this.serializeArray();
        $(array).each(function () {
            if (this.name.match(/bifile_*/g)) {
                files[this.name] = this.value;
            } else {
                if (serializeObj[this.name]) {
                    if ($.isArray(serializeObj[this.name])) {
                        serializeObj[this.name].push(this.value);
                    } else {
                        serializeObj[this.name] = [serializeObj[this.name], this.value];
                    }
                } else {
                    serializeObj[this.name] = this.value;
                }
            }
        });
        return $.extend(files, {data: JSON.stringify(serializeObj)});
    }

    $.fn.serializeJs = function () {
        var serializeObj = {}, files={};
        var array = this.serializeArray();
        var $this = this;
        $(array).each(function () {
            if (this.name.match(/bifile_*/g)) {
                files[this.name] = this.value;
            } else {
                if (serializeObj[this.name]) {
                    if ($.isArray(serializeObj[this.name])) {
                        serializeObj[this.name].push(this.value);
                    } else {
                        serializeObj[this.name] = [serializeObj[this.name], this.value];
                    }
                } else {
                    var sv = $this.find("select[name='" + this.name + "']").find("option:selected").text();
                    if ($.trim(sv)!="") {
                        serializeObj[this.name + "Txt"] = sv;
                    }
                    if($.trim(this.value)!=""){
                        serializeObj[this.name] = this.value;
                    }

                }
            }
        });
        var arrfiles = Object.keys(files);
        if (arrfiles.length) {serializeObj["file"] = JSON.stringify(files);}

        return serializeObj;
    };

})(jQuery)





